// Definition for singly-linked list.
function ListNode(val, next) {
  this.val = val === undefined ? 0 : val;
  this.next = next === undefined ? null : next;
}

// 创建头节点
let head = new ListNode(1);
let currentNode = head;

for (let i = 2; i <= 5; i++) {
  currentNode.next = new ListNode(i);
  currentNode = currentNode.next;
}

/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function (head, n) {
  let length = 0;
  let current = head;

  while (current !== null) {
    length++;
    current = current.next;
  }
  console.log(length);
  if (length === n) return head.next;
  else {
    current = head;
    for (let i = 0; i < length - n - 1; i++) current = current.next;
    current.next = current.next.next;
  }

  return head;
};

currentNode = removeNthFromEnd(head, 2);
while (currentNode !== null) {
  console.log(currentNode.val);
  currentNode = currentNode.next;
}
